package com.pw.gmall.realtime.utils;

import com.pw.gmall.realtime.entities.OrderInfo;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: linux_future
 * @since: 2022/3/18
 **/
public class JdbcUtils {
    public static Connection getJdbcConnect(String driver,
                                            String url,
                                            String user,
                                            String password) throws Exception {
        // 获取jdbc连接, 步骤
        // 1. 加载驱动
        Class.forName(driver);
        // 2. 获取连接
        return DriverManager.getConnection(url, user, password);
    }

    public static <T> List<T> queryList(Connection conn, String sql, Object[] args, Class<T> cls) throws Exception {
        ArrayList<T> result = new ArrayList<>();
        PreparedStatement ps = conn.prepareStatement(sql);
        //遍历赋值
        for (int i = 0; args != null && i < args.length; i++) {
            Object arg = args[i];
            ps.setObject(i + 1, arg);
        }
        ResultSet rs = ps.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        while (rs.next()) {
            T t = cls.newInstance();
            int columnCount = metaData.getColumnCount();
            for (int i = 0; i < columnCount; i++) {
                String columnName = metaData.getColumnLabel(i+1);
                Object columnValue = rs.getObject(i+1);
                BeanUtils.setProperty(t, columnName, columnValue);
            }
            result.add(t);
        }
        ps.close();
        return result;
    }

    public static void main(String[] args) throws Exception {
        Connection conn = getJdbcConnect("com.mysql.cj.jdbc.Driver", "jdbc:mysql://hadoop162:3306/gmall2022", "root", "aaaaaa");
        String sql = "select * from order_info";
        List<OrderInfo> list = queryList(conn, sql, null, OrderInfo.class);
        System.out.println(list);

    }

}
